$(function() {
	// 故障统计页面时间初始化
	initFaultCountQueryYear();
	// 故障综合原因页面时间初始化
	initFaultReasonQueryYear();
	// 故障具体原因页面时间初始化
	initFaultDetailReasonQueryYear();
	var d = new Date();
	var currentYear=d.getFullYear();
	$("#year").val(currentYear);
	var t1 = window.setInterval(function() {
		// 获取输电线路历史故障次数
		getLineFaultsCountData();
		var w = $('#pane1').width() + "";
		if (w != '0') {
			var width = $("#pane1").css('width');
			$("#faultNumLine").css("width", width / 2);
			$("#lineOperation").css("width", width / 2);
			window.clearInterval(t1);
		}
	}, 20);
	getDatas();
});

// 故障统计页面时间初始化
function initFaultCountQueryYear() {
	var d = new Date();
	var currentYear=d.getFullYear();
	$('#firstYear').val(currentYear-5);
	$('#firstYear').datetimepicker({
		startView: 4,
		minView:4,
		autoclose : true,
		format : 'yyyy'
	});
	$('#lastYear').val(currentYear);
	$('#lastYear').datetimepicker({
		startView: 4,
		minView:4,
		autoclose : true,
		format : 'yyyy'
	});
}
// 故障类型统计页面时间初始化
function initFaultDeviceCountQueryYear() {
	var d = new Date();
	var currentYear=d.getFullYear();
	// 输电线路故障类型统计——年份
	$('#year_id').val(currentYear);
	$('#year_id').datetimepicker({
		startView: 4,
		minView:4,
		autoclose : true,
		format : 'yyyy'
	});
}

// 故障综合原因页面时间初始化
function initFaultReasonQueryYear() {
	var d = new Date();
	var currentYear=d.getFullYear();
	$('#year').val(currentYear);
	$('#year').datetimepicker({
		startView: 4,
		minView:4,
		autoclose : true,
		format : 'yyyy'
	});
}

// 故障具体原因页面时间初始化
function initFaultDetailReasonQueryYear() {
	var d = new Date();
	var currentYear=d.getFullYear();
	$('#startYear').val(currentYear);
	$('#startYear').datetimepicker({
		startView: 4,
		minView:4,
		autoclose : true,
		format : 'yyyy'
	});
	$('#endYear').val(currentYear);
	$('#endYear').datetimepicker({
		startView: 4,
		minView:4,
		autoclose : true,
		format : 'yyyy'
	});
}

//$("#tab2").click(function() {
//	var width = parseInt($("#pane2").css('width')) - 18;
//	var selectedYear1 = $("#year").val();
//	barChartCanvas.getChart().resize();
//	pchar.getChart().resize();
////	fault_month_line.getChart().resize();
//});


$("#faultDeviceLi").click(function(){
//	$.ajaxSettings.async = false;
	initFaultDeviceCountQueryYear();
	getFaultTypeDataByYear();
//	$.ajaxSettings.async = true;
});

// 输电线路故障类型分析
var faultTypeYears = [];

//按照年升序排列
function yearSortAsc(a,b) {
	return a - b;
}
//按照年升序排列
var by = function(name) {
	 return function(o, p){
	   var a, b;
	   if (typeof o === "object" && typeof p === "object" && o && p) {
	     a = o[name];
	     b = p[name];
	     if (a === b) {
	       return 0;
	     }
	     if (typeof a === typeof b) {
	       return a < b ? -1 : 1;
	     }
	     return typeof a < typeof b ? -1 : 1;
	   }
	   else {
	     throw ("error");
	   }
	}
}

// 获取输电线路历史故障次数
function getLineFaultsCountData() {
	var startYear = $("#firstYear").val();
	var endYear = $("#lastYear").val();
	var indexV = document.getElementById("queryForm:vol").selectedIndex; // 获取当前选择项的索引
	var voltage = document.getElementById("queryForm:vol").options[indexV].value; // 获取当前选择项的值
	$.getJSON('/rest/transmissionline/getLineFaultCountData/'+startYear+'/'+endYear+'/'+voltage, function(result) {
		result.sort(by("year"));
		faultNum(result);
		lineRun(result);
	});
}

// 输电线路历史故障次数统计折线图
function faultNum(data) {
	var falutNum = [];
	faultTypeYears = [];
	for ( var i in data) {
		faultTypeYears.push(data[i].year);
		falutNum.push(data[i].value.faultNum);
	};
	var faultNumChart = new CategoryLine("faultNumLine");
	faultNumChart.setxAxis(faultTypeYears);
	faultNumChart.setyAxis(falutNum);
	faultNumChart.setxAxisTitle('年份');
	faultNumChart.setyAxisTitle('故障次数');
	faultNumChart.setyAxisName('故障次数');
//	faultNumChart.setTitle('输电线路历史故障次数统计');
//	var opt = faultNumChart.getOption(); 
//	opt.title.left = 'center'; // 标题位置
//	opt.grid.top = '30%'; // 图形位置
//	opt.legend.top = '10%'; // 图标位置
	faultNumChart.show();
}

//故障次数月度统计
var fault_month_line ;
function initCountMonthChart(result){
     var xValues = [];
     for(var i=1;i<13;i++){
    	 xValues.push(i+"月");
     }
     fault_month_line = new CategoryLine('fault_month_line');
     fault_month_line.setxAxis(xValues).setyAxis(result.months);
     var opt = fault_month_line.getOption();
     opt.series[0].label.normal.position = "top";
     fault_month_line.setxAxisTitle("月份");
     fault_month_line.setyAxisTitle("次数");
     fault_month_line.setyAxisName('次数');
     fault_month_line.show();
}

// 输电线路运行情况
function lineRun(data) {
	var yleftname = '线路总长';
	var yrightname = '年故障率';
	var yaddname = '新增长度';
	var legendLabels = [ '年故障率', '线路总长', '新增长度' ];
	var faultRate = [];
	// 线路总长
	var totalLength = [];
	// 新增长度
	var newAddLength = [];
	for ( var i in data) {
		faultRate.push(Number(data[i].value.faultRate).toFixed(2));
		totalLength.push(data[i].value.lineLength);
		newAddLength.push(data[i].value.newAddLength);
	}
	$('.lineRunTitle').html('输电线路运行情况');
	var lineRunChart = new Echarts3LineBars('lineOperation');
	lineRunChart.setLegendLabels(legendLabels);
	lineRunChart.setNumber(totalLength);
	lineRunChart.setRatio(faultRate);
	lineRunChart.setYears(faultTypeYears);
	lineRunChart.setYleftname(yleftname);
	lineRunChart.setYrightname(yrightname);
	lineRunChart.setLeftyAxisTitle('线路总长/km');
	lineRunChart.setRightyAxisTitle('年故障率(次/百公里·年)');
	lineRunChart.setYaddname(yaddname);
	lineRunChart.setAdd(newAddLength);
	lineRunChart.show();
}

// 按年份获取故障类型数据
function getFaultTypeDataByYear() {
	// 输电线路故障类型统计年份选择
	var year = $("#year_id").val();
	var index = document.getElementById("queryForm1:vol1").selectedIndex;
	var voltage = document.getElementById("queryForm1:vol1").options[index].value;
	$.getJSON('/rest/transmissionline/getLineFaultByYearAndVoltage/' + year + '/' + voltage, function(result) {
//		$.getJSON('/rest/transmissionline/getLineFaultTypeDataByYear/' + year, function(result) {
		faultTypePie(result);
		faultTypeCompany(result);
	});
}

// 故障类型占比
function faultTypePie(datas) {
	if(datas[0].faultType.length==0) {
		$("#faultTypePie").html("该时间暂无数据信息");
	} else {
		var faultTypeData = [];
		for ( var i in datas[0].faultType) {
			var num = [];
			num.push(datas[0].faultType[i]);
			num.push(0);
			faultTypeData.push(num);
		}
		for ( var i in faultTypeData) {
			for (var j = 1; datas.length > j; j++) {
				faultTypeData[i][1] += parseInt(datas[j].value[i]);
			}
		}
		var faultTypePie = new Pie('faultTypePie');
		faultTypePie.setPie(faultTypeData).setPieOuterRadius('50%');
		var option = faultTypePie.getOption();
		option.grid.top=80;
		option.title.textStyle.fontSize = 16;
		option.title.textStyle.fontWeight = 'normal';
		option.legend.orient = 'vertical';
		faultTypePie.setPieOuterRadius('50%').setLegendPosition('left', 'top').setPieLabelFormatter("{b}: {c} ({d}%)").setTitlePosition('center');
		faultTypePie.show();
	}
}
// 按公司故障类型统计
function faultTypeCompany(datas) {
	if(datas[0].faultType.length==0) {
		$("#faultTypeCompany").html("该时间暂无数据信息");
	} else {
		var faultTypeData = {
				name : '',
				xData : {
					name : '单位',
					value : []
				},
				yData : {
					name : '次数',
					value : []
				}
		};
		for (var i = 1; datas.length > i; i++) {
			faultTypeData.xData.value.push(datas[i].name);
		}
		for ( var j in datas[0].faultType) {
			var obj = {};
			obj["lineValue"] = [];
			obj["lineName"] = datas[0].faultType[j];
			for (var i = 1; datas.length > i; i++) {
				obj["lineValue"].push(datas[i].value[j]);
			}
			faultTypeData.yData.value.push(obj);
		}
		var faultTypeCompanyBar = new CategoryBar('faultTypeCompany')
		var opt = faultTypeCompanyBar.getOption();
		opt.tooltip.axisPointer.type = "shadow";
		opt.grid.top = '30%'; // 图形位置
		opt.grid.bottom=40;
		opt.legend.top='5%'; // 图标位置
		opt.title.textStyle.fontSize = 16;
		opt.title.textStyle.fontWeight = 'normal';
		faultTypeCompanyBar.setTitlePosition('center').setDataZoomStartValue(0,5);
		faultTypeCompanyBar.setData(faultTypeData);
		faultTypeCompanyBar.show();
	}
}

/**
 * 故障综合原因tab页js
 */
$("#li2").click(function(){
	initFaultReasonQueryYear();
	onYearChanged();
});

onYearChanged();
function onYearChanged() {
	var year = $("#year").val();
	$('#pane2 .year').html(year);
	var index = document.getElementById("queryForm2:vol2").selectedIndex;
	var voltage = document.getElementById("queryForm2:vol2").options[index].value;
	getDataByYear(year,voltage);
}
//根据年获取一年12个月故障类型数据
function getDataByYear(year,voltage){
	$.getJSON('/rest/transmissionline/getLineFaultByYear/' + year + '/' + voltage, function(result) {
		console.log(result);
		initCountMonthChart(result);
		initReasonCountMonthChart(result);
	});
	
}

//故障原因次数按月统计
var barChartCanvas;
var pchar;
function initReasonCountMonthChart(result){
	if(result.faultReasonTotalCounts.length==0) {
		$("#chart_fault_all_bar").html("该时间暂无数据信息");
		$("#chart_fault_all_bar_ring").html("该时间暂无数据信息");
	} else {
		// 故障原因占比统计
		var faultMonthdata = {
				name : '',
				xData : {
					name : '月份',
					value : [ '1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月',
						'11月', '12月' ]
				},
				yData : {
					name : '次数',
					value : []
				}
		};
		for(var faultReason in result.faultReasonCounts){
			var obj1={
					lineName:'',
					lineValue:[]
			};
			obj1.lineName=faultReason;
			obj1.lineValue=result.faultReasonCounts[faultReason];
			faultMonthdata.yData.value.push(obj1);
		}
		barChartCanvas = new CategoryBar("chart_fault_all_bar");
		var opt = barChartCanvas.getOption();
		opt.tooltip.axisPointer.type = "shadow";
		barChartCanvas.setMagicType(false).setZoomTool(false).setRestore(false);
		barChartCanvas.setDataZoom(true);
		barChartCanvas.setDataZoomStartValue(0,5);
		barChartCanvas.setData(faultMonthdata).show();
		
		pchar = new Pie("chart_fault_all_bar_ring");
		pchar.setPie(result.faultReasonTotalCounts);
		var option = pchar.getOption();
		option.legend.orient = 'vertical';
		pchar.setPieOuterRadius('50%').setLegendPosition('left', 'top').setPieLabelFormatter("{b}: {c} ({d}%)").show();
	}
}

